import React, { useState, useEffect } from 'react';
import { CgCode } from 'react-icons/cg';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Alert, AlertDescription } from './ui/alert';
import { Progress } from './ui/progress';
import { Label } from './ui/label';
import { getVsCodeApi } from '../lib/vscode-api';

interface NpmBuildSectionProps {
  projectPath: string;
  privateKeyPath: string;
  appid: string;
  type: string;
  showToast: (title: string, description: string, type: 'success' | 'error' | 'info') => void;
  setLoading: (loading: boolean) => void;
}

const NpmBuildSection: React.FC<NpmBuildSectionProps> = ({
  projectPath,
  privateKeyPath,
  appid,
  type,
  showToast,
  setLoading,
}) => {
  const [progress, setProgress] = useState<number>(0);
  const [logs, setLogs] = useState<string[]>([]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      const message = event.data;
      
      switch (message.command) {
        case 'buildProgress':
          if (message.data) {
            setProgress(message.data.progress);
            setLogs(prev => [...prev, message.data.step]);
          }
          break;
          
        case 'buildResult':
          setLoading(false);
          if (message.data.success) {
            showToast('构建成功', 'npm 构建已完成', 'success');
          } else {
            showToast('构建失败', message.data.error || '未知错误', 'error');
          }
          break;
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [showToast, setLoading]);

  const handleNpmBuild = async () => {
    if (!projectPath) {
      showToast('错误', '请先选择项目路径', 'error');
      return;
    }

    setLoading(true);
    setProgress(0);
    setLogs([]);
    
    // 发送npm构建请求到扩展
    getVsCodeApi().postMessage({
      command: 'npmBuild',
      data: { projectPath }
    });
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <CgCode className="h-5 w-5" />
            构建 NPM
          </CardTitle>
          <CardDescription>
            构建小程序中的 npm 依赖，生成可在小程序环境中使用的包
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Alert>
            <AlertDescription>
              此操作会构建项目中的 npm 依赖，确保 package.json 中已正确配置依赖。
            </AlertDescription>
          </Alert>

          {logs.length > 0 && (
            <div className="space-y-2">
              <Label>构建日志</Label>
              <div className="bg-gray-100 dark:bg-gray-800 p-4 rounded-md space-y-1">
                {logs.map((log, index) => (
                  <div key={index} className="text-sm font-mono">
                    {log}
                  </div>
                ))}
              </div>
            </div>
          )}

          {progress > 0 && (
            <div className="space-y-2">
              <Label>构建进度</Label>
              <Progress value={progress} />
            </div>
          )}

          <Button 
            onClick={handleNpmBuild}
            disabled={!projectPath}
            className="w-full"
          >
            开始构建 NPM
          </Button>
        </CardContent>
      </Card>
    </div>
  );
};

export default NpmBuildSection;